package com.crrcdt.mail.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crrcdt.mail.constant.MailConstants;
import com.crrcdt.mail.entity.Employee;
import com.crrcdt.mail.entity.MailSendLog;
import com.crrcdt.mail.service.EmployeeService;
import com.crrcdt.mail.service.MailSendLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class MailSendTask {
    @Autowired
    MailSendLogService mailSendLogService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    EmployeeService employeeService;
    //10s 任务调度一次
    @Scheduled(cron = "0/20 * * * * ?")
    public void mailResendTask() {
        final List<MailSendLog> logs = mailSendLogService.list(new QueryWrapper<MailSendLog>().eq("status", 0).lt("tryTime",DateUtil.parse(DateUtil.now())));
        if (logs == null || logs.size() == 0) {
            return;
        }
        logs.forEach(mailSendLog->{
            if (mailSendLog.getCount() >= 3) {
                mailSendLog.setStatus(2);
                //直接设置该条消息发送失败
                mailSendLogService.updateById(mailSendLog);
            }else{
                mailSendLog.setCount(mailSendLog.getCount()+1);
                mailSendLog.setUpdateTime(DateUtil.parse(DateUtil.now()));
                mailSendLogService.updateById(mailSendLog);
                final Employee employee = employeeService.getById(mailSendLog.getEmpId());
                //如果发送的是一个对象，则使用序列化机制，对象必须实现序列化
                //TODO 发送消息p->b(监听队列)broker代理发给指定的exchange，然后exchange与queue根据路由规则进行绑定，（根据路由规则发给指定的queue,消费端只要监听指定的queue）
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME, employee, new CorrelationData(mailSendLog.getMsgId()));
            }
        });
    }
}
